package com.imachen.ymcc.exception;

import com.imachen.ymcc.result.JSONResult;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobleExceptionHandle {

    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        // indexOf：等于-1不包含，不等于-1包含
        if (e.getClass().getSimpleName().indexOf("AccessDeniedException") != -1){
            return JSONResult.error(GlobalExceptionCode.USER_NO_PERMISSION_ERROR);
        }
        e.printStackTrace();
        log.error("全局的异常捕捉-customException方法，发生异常，异常信息为：{}", e.getMessage());
        return JSONResult.error(GlobalExceptionCode.ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult GlobalCustomExceptionHandler(GlobalCustomException e){
        return JSONResult.error(e);

    }

    // 我们指定捕捉MethodArgumentNotValidException异常类型
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult customException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer sber = new StringBuffer();
        allErrors.forEach(obj->{
            sber.append("参数校验失败，失败原因为：").append(obj.getDefaultMessage()).append(";");
        });
        return JSONResult.error(sber.toString(), "1000");
    }

}
